import axios from 'axios'
import store from '../store'
import { Toast } from 'vant'
//  创建一个 axios 实例，将来对创建出来的实例，进行自定义配置
//  好处：不会污染原始的 axios 对象
const instance = axios.create({
  baseURL: 'http://smart-shop.itheima.net/index.php?s=/api',
  timeout: 5000
})

// 自定义配置

// Add a request interceptor
instance.interceptors.request.use(function (config) {
  // Do something before request is sent
  Toast.loading({
    message: '加载中...',
    forbidClick: true,
    loadingType: 'spinner',
    duration: 0
  })

  // 只要有token，就在请求时，把token添加到请求头中
  const token = store.getters.token
  if (token) {
    config.headers['Access-Token'] = token
    config.headers.platform = 'H5'
  }
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})

// Add a response interceptor
instance.interceptors.response.use(function (response) {
  // Any status code that lie within the range of 2xx cause this function to trigger
  // Do something with response data
  const res = response.data
  if (res.status !== 200) {
    // 给错误提示， Toast默认是单例模式
    Toast.fail(res.message || 'Error')
    // 抛出一个错误的promise对象
    return Promise.reject(res.message || 'Error')
  } else {
    // 正确情况，直接走业务核心逻辑 关闭提示
    Toast.clear()
  }
  return res
}, function (error) {
  // Any status codes that falls outside the range of 2xx cause this function to trigger
  // Do something with response error
  return Promise.reject(error)
})

// 导出配置好的实例
export default instance
